/*
 * @Author: your name
 * @Date: 2020-06-04 16:57:47
 * @LastEditTime: 2020-12-23 13:08:43
 * @LastEditors: Please set LastEditors
 * @Description: 二维码下载
 * @FilePath: \webManage\src\api\dowloadCode.js
 */

// 下载
function downloadQrCode (dName) {
  let myselfCanvas = document.getElementById('qrcode').getElementsByTagName('canvas')
  let img = document.getElementById('qrcode').getElementsByTagName('img')
  let a = document.createElement('a')
  let imgURL = myselfCanvas[0].toDataURL('image/jpg')
  let u = navigator.userAgent
  if (u.indexOf('Trident') !== -1 && u.indexOf('Windows') !== -1) {
    let bstr = atob(imgURL.split(',')[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    let blob = new Blob([u8arr])
    window.navigator.msSaveOrOpenBlob(blob, '二维码' + '.' + 'png')
  } else if (u.indexOf('Firefox') > -1) {
    let blob = base64ToBlob(imgURL)
    let evt = document.createEvent('HTMLEvents')
    evt.initEvent('click', true, true)
    a.download = ' '
    a.href = URL.createObjectURL(blob)
    a.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }))
  } else {
    img.src = myselfCanvas[0].toDataURL('image/jpg')
    a.href = img.src
    a.download = dName
    a.click()
  }
}
// base64转blob
function base64ToBlob (code) {
  let parts = code.split(';base64,')
  let contentType = parts[0].split(':')[1]
  let raw = window.atob(parts[1])
  let rawLength = raw.length
  let uInt8Array = new Uint8Array(rawLength)
  for (let i = 0; i < rawLength; ++i) {
    uInt8Array[i] = raw.charCodeAt(i)
  }
  return new Blob([uInt8Array], { type: contentType })
}

export default {
  downloadQrCode
}
